package com.axc.gallery2.edit;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

import com.axc.gallery2.R;
import com.axc.gallery2.album.AlbumListViewActivity;
import com.axc.gallery2.edit.color.ToChangeColor;
import com.axc.gallery2.function.IPicEdit5;
import com.axc.gallery2.function.ISaveChange;
import com.axc.gallery2.function.IsetImage;

public class ColorAdjust extends Activity implements OnClickListener,
		OnSeekBarChangeListener, ISaveChange, IsetImage {
	// 色相、 饱和度、 明度
	private SeekBar seekhue = null;
	private SeekBar seeksaturation = null;
	private SeekBar seekbright = null;

	// 创建Bitmap以备获取图片数据
	private Bitmap bitmap;
	private Bitmap ReBitmap;
	private Bitmap changeBitmap;
	private ImageView imageview1 = null;

	private int maxBarValue = 255;

	// 调整值
	public final int FLAG_SATURATION = 0x0;
	public final int FLAG_LUM = 0x1;
	public final int FLAG_HUE = 0x2;
	private float mLumValue = 1F;
	private float mSaturationValue = 0F;
	private float mHueValue = 0F;
	private static final int MIDDLE_VALUE = 127;
	private ImageButton btnVisMenu;

	LinearLayout bottomMenu;
	LinearLayout headLayout; 

	// 获取Linearlayou来设置层的显示与隐藏
	private LinearLayout linear = null;

	/**
	 * 自动搜索ImageView<b>根据LinearLayout搜索子控件ImageView</b> <b>getImageView 关联
	 * CreateImageViewMenu</b>
	 * 
	 * @param needview
	 *            传入LinearLayout
	 * @param listener
	 *            传入监听事件
	 */
	public void getImageView(LinearLayout needview, OnClickListener listener) {
		for (int i = 0; i < needview.getChildCount(); i++) {
			View v = needview.getChildAt(i);
			if (v instanceof ImageView) {
				ImageView view = (ImageView) needview.getChildAt(i);
				view.setOnClickListener(listener);
				// 如需要获取按钮则添加 btnMains.add();
			}
		}
	}

	/**
	 * 自动搜索ImageView<b>根据LinearLayout搜索子控件ImageView</b> <b>getImageView 关联
	 * CreateImageViewMenu</b>
	 * 
	 * @param needview
	 *            传入LinearLayout
	 * @param listener
	 *            传入监听事件
	 */
	public void CreateImageViewMenu(LinearLayout linearView, int id,
			OnClickListener listener) {
		linearView = (LinearLayout) findViewById(id);
		for (int i = 0; i < linearView.getChildCount(); i++) {
			View v = linearView.getChildAt(i);
			if (v instanceof LinearLayout) {
				LinearLayout linear = (LinearLayout) linearView.getChildAt(i);
				//getImageView(linear, listener);
				linear.setOnClickListener(listener);
				linear.setOnTouchListener(new OnTouchListener() {
					
					@Override
					public boolean onTouch(View v, MotionEvent event) {
						// TODO Auto-generated method stub
						switch (event.getAction()) {
						case MotionEvent.ACTION_DOWN:
							v.setBackgroundColor(Color.rgb(236, 102, 13)); 
							break;
						case MotionEvent.ACTION_UP:
							v.setBackgroundColor(R.color.transparent);
							break;
						case MotionEvent.ACTION_CANCEL:
							v.setBackgroundColor(R.color.transparent);
							break;
						default:
							break;
						}
						return false;
					}
				});
			}
		}
	}

	//主题应用
	public static ColorAdjust Talbum;
	public int theme = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // 主题
        Talbum = this;
        theme = getSharedPreferences("cons", MODE_PRIVATE).getInt("theme",
                android.R.style.Theme);
        setTheme(theme);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.edit_color_adjust);
		
		
		// CreateImageViewMenu(bottomMenu, R.id.edit_bottomen, this);
		BottomMenuClickListener bottomMenu = new BottomMenuClickListener();
		bottomMenu.run();
 
		headLayout=(LinearLayout)findViewById(R.id.linearColor); 
		
		// 布局文件
		linear = (LinearLayout) findViewById(R.id.scrollrgb);
		imageview1 = (ImageView) findViewById(R.id.imageview_scroll);

		/**
		 * 获取图片
		 */
		bitmap=new ToReleaseBitmap().RelBmp(EditActivity.imageFileNames);//BitmapFactory.decodeFile(EditActivity.imageFileNames);
		//bitmap = ((BitmapDrawable) this.getResources().getDrawable(R.drawable.girl)).getBitmap();
		// 设置Imageview图片
		imageview1.setImageBitmap(bitmap);
		// 重设图片
		changeBitmap = ReBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap
				.getWidth(), bitmap.getHeight());

		createSeekbar();
	}

	// 让他点击色彩时才创建（now） 但之后多次按下会多次创建的，那要进程启动时创建还是按下才创建
	public void createSeekbar() {
		seekhue = (SeekBar) findViewById(R.id.seekBarHub);
		seekhue.setMax(maxBarValue);

		seeksaturation = (SeekBar) findViewById(R.id.seekBarsaturation);
		seeksaturation.setMax(maxBarValue);

		seekbright = (SeekBar) findViewById(R.id.seekBarBright);
		seekbright.setMax(maxBarValue);

		setMiddle();

		seekhue.setOnSeekBarChangeListener(this);
		seeksaturation.setOnSeekBarChangeListener(this);
		seekbright.setOnSeekBarChangeListener(this);
	}

	public void setMiddle() {
		seekbright.setProgress(MIDDLE_VALUE);
		seeksaturation.setProgress(MIDDLE_VALUE);
		seekhue.setProgress(MIDDLE_VALUE);
	}

	// ColorFunctionControl cFunctionControl = new ColorFunctionControl(this);
	// FunctionAdapter functionAdapter=new FunctionAdapter(this,this);
	int fisrtbar = 1;
	IPicEdit5 picEdit5 = new ToChangeColor();

	@Override
	public void onProgressChanged(SeekBar seekBar, int progress,
			boolean fromUser) {
		// TODO Auto-generated method stub

		int selectID = 0x0;
		switch (seekBar.getId()) {
		case R.id.seekBarHub:
			selectID = FLAG_HUE;
			setHue(progress);
			changeBitmap = picEdit5.ProcessWork(bitmap, selectID, mHueValue,
					mSaturationValue, mLumValue);
			break;
		case R.id.seekBarsaturation:
			selectID = FLAG_SATURATION;
			changeBitmap = picEdit5.ProcessWork(bitmap, selectID, mHueValue,
					mSaturationValue, mLumValue);
			setSaturation(progress);
			break;
		case R.id.seekBarBright:
			selectID = FLAG_LUM;
			changeBitmap = picEdit5.ProcessWork(bitmap, selectID, mHueValue,
					mSaturationValue, mLumValue);
			setLum(progress);
			break;
		}
		imageview1.setImageBitmap(changeBitmap);
		// functionAdapter.ProcessImage(new ToChangeColor());
		// functionAdapter.setImage(bitmap, selectID, mHueValue,
		// mSaturationValue, mLumValue);
	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub
	}

	/**
	 * 设置饱和度值
	 * 
	 * @param saturation
	 */
	public void setSaturation(int saturation) {
		mSaturationValue = saturation * 1.0F / MIDDLE_VALUE;
	}

	/**
	 * 设置色相值
	 * 
	 * @param hue
	 */
	public void setHue(int hue) {
		mHueValue = hue * 1.0F / MIDDLE_VALUE;
	}

	/**
	 * 设置亮度值
	 * 
	 * @param lum
	 */
	public void setLum(int lum) {
		mLumValue = (lum - MIDDLE_VALUE) * 1.0F / MIDDLE_VALUE * 180;
	}

	// 设置Imageviwe
	@Override
	public void SetImageview() {
		// imageview1.setImageBitmap(functionAdapter.getBitmap());
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_Reset:
			bitmap = ReBitmap;
			imageview1.setImageBitmap(bitmap);
			setMiddle();
			break;
		/*case R.id.btnVisMenu:
			setColorBarVisibility();
			break;*/
		case R.id.btn_Cancle:
			ColorAdjust.this.finish();
			break;
		case R.id.btn_Home:
			Intent intent=new Intent();
			intent.setClass(ColorAdjust.this, AlbumListViewActivity.class);
			ColorAdjust.this.startActivity(intent);
			ColorAdjust.this.finish();
			EditActivity.edit1.finish();
			break;
		case R.id.btn_acolor:
			if (linear.getVisibility() == View.INVISIBLE) {
				linear.setVisibility(View.VISIBLE);
			} else {
				linear.setVisibility(View.INVISIBLE);
			}
			break;
		case R.id.btn_Save:
			new SaveBitmap().Save(ColorAdjust.this, changeBitmap);
			break; 
		default:
			break;
		}
	}
	
 
	/*public static void killAll(Context context) {

		 //获取一个ActivityManager 对象
		        ActivityManager activityManager = (ActivityManager) context
		                        .getSystemService(Context.ACTIVITY_SERVICE);

	    //获取系统中所有正在运行的进程

		       List<RunningAppProcessInfo> appProcessInfos = activityManager
		                        .getRunningAppProcesses();

	  //获取当前activity所在的进程
		      String currentProcess=context.getApplicationInfo().processName;

		//对系统中所有正在运行的进程进行迭代，如果进程名不是当前进程，则Kill掉
		       for (RunningAppProcessInfo appProcessInfo : appProcessInfos) {
		      String processName=appProcessInfo.processName;
		   if (!processName.equals(currentProcess)) { 
              activityManager.killBackgroundProcesses(processName);
		   　　　　}
		        　　}
		　　} 
*/

	public void setColorBarVisibility() {
		if (linear.getVisibility() == View.INVISIBLE) {
			linear.setVisibility(View.VISIBLE);
		} else {
			linear.setVisibility(View.INVISIBLE);
		}
	}
 
	class BottomMenuClickListener implements Runnable {

		@Override
		public void run() { 
			// TODO Auto-generated method stub
			CreateImageViewMenu(bottomMenu, R.id.edit_bottomen,
					ColorAdjust.this);
			btnVisMenu = (ImageButton) findViewById(R.id.btnVisMenu);
			//btnVisMenu.setAlpha(100);
			btnVisMenu.setOnClickListener(ColorAdjust.this);
		}

	}
	//侦听用户的点击返回键,提示程序退出
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    // TODO Auto-generated method stub
	    
	    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
	    	Intent intent = new Intent();
			intent.setClass(ColorAdjust.this, EditActivity.class);
			startActivity(intent); 
            return true;
        }
	    return false;
	}
	@Override
	public void SaveChange() {
		// TODO Auto-generated method stub
		
	}
}
